<?php

class CategoryControl extends Control {

    //分类管理
    public function category() {
//        showMinus
//        showPlus
        $data = M('category')->query('select * from hd_category');
        $data = $this->all_cate($data);
        $this->assign('data', $data);
        $this->display();
    }

    //添加顶级分类
    public function add_top_cate() {
        if (IS_POST) {
            $data = array(
                'title' => adds_html($_POST['title']),
                'pid' => 0
            );
            if (M('category')->add($data)) {
                $this->success('添加成功！', __ROOT__ . '?c=Category&m=category');
            } else {
                $this->error('添加失败！');
            }
        }
        $this->display();
    }

    public function add_cate() {
        if (IS_POST) {
            $pid = (int) $_GET['pid'];
            $data = array(
                'title' => adds_html($_POST['title']),
                'pid' => $pid
            );
            if (M('category')->add($data)) {
                $this->success('添加成功！', __ROOT__ . '?c=Category&m=category');
            } else {
                $this->error('添加失败！');
            }
        }
        $this->display();
    }

    public function edit_cate() {
        if (IS_POST) {
            $cid = (int) $_POST['cid'];
            $data = array(
                'title' => adds_html($_POST['title']),
                'pid' => adds_html($_POST['pid'])
            );
            M('category')->where('cid=' . $cid)->update($data);
            $this->success('编辑成功！', __ROOT__ . '?c=Category&m=category');
        }
        $cid = (int) $_GET['cid'];
        $data = M('category')->query('SELECT * FROM hd_category where cid=' . $cid);
        $this->assign('data', $data[0]);
        $this->display();
    }

    public function del_cate() {
        $cid = (int) $_GET['cid'];
        if (M('category')->where('pid=' . $cid) && M('category')->where('cid=' . $cid)->del()) {
            $this->success('删除成功！', __ROOT__ . '?c=Category&m=category');
        } else {
            $this->error('删除失败');
        }
    }

    public function all_cate($data, $pid = 0, $level = 0, $html = 0) {
        $newData = array();
        foreach ($data as $v) {
            //如果当前循环的数组的pid和传入的参数一样，则执行循环，也就是pid值一样，则循环
            if ($v['pid'] == $pid) {
                $v['level'] = $level;
                $v['html'] = str_repeat('_', ($level * 5));
                //将pid值为$pid的数组压入新的数组中
                $newData[] = $v;
                //合并之前新数组中的值和pid是当前cid的数组项，让父子级的数组靠在一起
                $newData = array_merge($newData, $this->all_cate($data, $v['cid'], $level + 1));
            }
        }
        return $newData;
    }

}
